class Solution(object):
    def minDays(self, grid):
        m = len(grid)
        n = len(grid[0])
        p = [i for i in range(m * n)]
        self.total = 0
        count = 0
        island = []

        def find(x):
            if x == p[x]:
                return p[x]
            else:
                p[x] = find(p[x])
                return p[x]

        def union(x, y):
            rx = find(x)
            ry = find(y)
            if rx != ry:
                self.total -= 1
                if rx > ry:
                    p[rx] = ry
                else:
                    p[ry] = rx

        for i in range(m):
            for j in range(n):
                if grid[i][j]:
                    self.total += 1
                    count += 1
                    if len(island) <= 2:
                        island.append((i, j))
                    for ux, uy in [(i - 1, j), (i, j - 1)]:
                        if 0 <= ux < m and 0 <= uy < n and grid[ux][uy]:
                            union(i * n + j, ux * n + uy)
        if self.total > 1 or self.total == 0:
            return 0
        if count <= 2:
            return count
        for i in range(m):
            for j in range(n):
                if grid[i][j]:
                    grid[i][j] = 0
                    now = island[0]
                    if now == (i, j):
                        now = island[1]
                    already = {now}
                    st = [now]
                    t = 0
                    while st:
                        next_st = []
                        for x, y in st:
                            t += 1
                            for ux, uy in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
                                if 0 <= ux < m and 0 <= uy < n and grid[ux][uy] and (ux, uy) not in already:
                                    next_st.append((ux, uy))
                                    already.add((ux, uy))
                        st = next_st
                    if t + 1 < count:
                        return 1
                    grid[i][j] = 1

        return 2

data = Solution()
grid = [[1,1],[1,0]]
print(data.minDays(grid))
